<template>
  <div class="examinationResultsWrap">
    <div class="pageTableInner">
      <div class="infoSearchWrap">
        <div class="infoSearchOne">
          <el-row :gutter="0">
            <el-col :span="9">
              <div class="searchWrap">
                <span class="searchFont">考核结果:</span>
                <span class="searchInputFont">
                 <el-select style="width: 100%;" v-model="searchElectricInfo.taskIdRe" size="mini"
                            @change="changeSelect('row')" placeholder="全部">
                      <el-option
                        v-for="item in options"
                        :key="item.id"
                        :label="item.examineName"
                        :value="item.id">
                      </el-option>
                    </el-select>
                </span>
              </div>
            </el-col>
            <div style="float: right;margin-right: 10px;">
              <span style="margin:0 10px;" v-if="$store.state.userInfo.roleLevel==1">
                <el-button type="primary" @click="getcurrentTempalteInfo" size="mini">初步考核结果（征求意见）</el-button>
                </span>
              <!--<el-button type="primary" size="mini" @click="getTempalteInfo()">导出</el-button>-->
              <affixBtn v-show="$store.state.btnMenuIds.indexOf(82)>-1&&searchElectricInfo.taskId"
                        :taskId="searchElectricInfo.taskId"></affixBtn>
            </div>
          </el-row>
        </div>
      </div>
      <div class="tableContainer" style="background-color:#EFEEF3;padding: 0; ">
        <div class="echartsWrap">
          <el-row :gutter="10" style="height: 100%;">
            <el-col :span="8" style="height: 100%;">
              <div style="background-color: white;padding: 20px 10px 0 10px;border-radius: 5px;height: 100%;">
                <div id="echartRecordResult" style="height: 100%;"></div>
              </div>
            </el-col>
            <el-col :span="16" style="height: 100%;">
              <div style="margin-bottom: 10px;background-color: white;padding: 20px 20px 10px 20px;border-radius: 5px;">
                <ridingCountEcharts ref="ridingEcharts" :perHourData="perHourData" :echartsNames="echartsNames"
                                    :perHour="perHour" :titleEcharts="titleEcharts1"></ridingCountEcharts>
              </div>
            </el-col>
          </el-row>
        </div>
        <div style="border-radius: 5px;padding: 20px 20px 100px 20px;background-color: white;margin-top: 30px;">
          <div class="tableInner" ref="tableInner">
            <el-table
              ref="multipleTable"
              :data="rows"
              stripe
              show-summary
              :summary-method="getSummaries"
              :height="tableHeight"
              :span-method="objectSpanMethod"
              tooltip-effect="dark"
            >
              <el-table-column
                label="指标类别"
                prop="classifyName"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                label="类别分值"
                prop="classifyScore"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="itemsName"
                label="指标项"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="standardScore"
                label="指标分值"
                show-overflow-tooltip
              >
              </el-table-column>

              <el-table-column
                v-for="(item,key) in tableCompanyList"
                :key="key"
                :label="item.enterpriseName"
                :prop="'value'+key"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <div style="cursor: pointer;"
                       @click="$refs.detailDialog.dialogOpen({itemsId:scope.row.itemsId,templateId:scope.row.enterpriseTotalList[key].templateId,taskId:scope.row.enterpriseTotalList[key].taskId,totalScore:scope.row.enterpriseTotalList[key].totalScore,enterpriseNo:scope.row.enterpriseTotalList[key].enterpriseNo})">
                    {{scope.row.enterpriseTotalList[key].totalScore}}
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

      </div>
    </div>
    <detailDialog ref="detailDialog"></detailDialog>
    <router-view :examineName="this.searchElectricInfo.examineName" :examineTask="examineTask"></router-view>
  </div>
</template>

<script>
  import ridingCountEcharts from './ridingCountEcharts.vue';
  import detailDialog from './detailDialog.vue';
  import affixBtn from './affixBtn.vue';
  export default {
    props: [],
    data(){
      return {
        perHourData: [],
        echartsNames: [],
        perHour: [],
        titleEcharts1: ["各企业历史考核分数", "分数(分)"],
        options: [],
        options1: [{
          value: '1',
          label: '2019年第一季度'
        }, {
          value: '2',
          label: '2018年第四季度'
        }, {
          value: '3',
          label: '2018年第三季度'
        }],
        rows: [],
        multipleSelection: [],
        examineData: [],
        //以下为搜索
        labelChecked: "",
        checkScore: 1,
        taskId: "",
        isEcharts: false,
        value6: "",
        examineTask: {},
        tableHeight: 400,
        spanArr: [],
        tableCompanyList: [],
        searchElectricInfo: {
          taskId: "",
          taskIdRe: "",
          examineName: "",
        },
      }
    },
    components: {ridingCountEcharts, detailDialog, affixBtn},
    created(){
      this.getTempalteInfo()
      //历史
      this.selectExamineHistory()

    },
    mounted(){
      this.$nextTick(() => {
        //表格滚动
        document.querySelector(".echartsWrap").style.height = document.querySelector(".examinationResultsWrap").clientHeight - 380 + "px"
        this.tableHeight = document.querySelector(".examinationResultsWrap").clientHeight - 370
      })
    },

    methods: {
//      切换考核任务结果
      changeSelect(){
        if (this.searchElectricInfo.taskIdRe) {
          this.searchElectricInfo.taskId = this.searchElectricInfo.taskIdRe
          this.options.forEach(item => {
            if (item.id == this.searchElectricInfo.taskIdRe) {
              this.getExamineInfo(item.templateId, item.id)
              this.titleEcharts1 = [item.examineName, "分数(分)"]
            }
          })
        } else {
          this.rows = []
        }

        //各期指标
        this.selectExamineItemGrade(this.searchElectricInfo.taskId)
      },
      selectExamineHistory(){
        this.axios.post(process.env.API_HOST + `/examine/selectExamineHistoryTotalGrade`, {})
          .then(response => {
            const result = response.data
            if (result.code == 200) {
              this.perHour = [], this.perHourData = [], this.echartsNames = [], this.titleEcharts1 = ["各企业历史考核分数", "分数(分)"]
              result.result.forEach((item, key) => {
                this.perHourData[key] = []
                item.examineList.forEach(item1 => {
                  if (key == 0) {
                    this.perHour.push(item1.examineName)
                  }
                  this.perHourData[key].push(item1.totalScore)
                })
                this.$store.state.companyInfos.forEach(item3 => {
                  if (item3.enterpriseNo == item.enterpriseNo) {
                    this.echartsNames.push(item3.enterpriseName)
                  }
                })
              })
            }
          })

      },
      selectExamineItemGrade(taskId){
        if (!taskId) {
          return
        }
        this.axios.post(process.env.API_HOST + `/examine/selectEnterpriseClassTotal`, {taskId: taskId})
          .then(response => {
            const result = response.data
            if (result.code == 200) {
              let indicatorData = [],dataArr=[]
              if (result.result.length > 0) {
                result.result.forEach((item, index) => {
                  dataArr[index]={
                    value: [],
                    name: item.enterpriseName
                  }
                  item.classTotalList.forEach(item1 => {
                      if (index == 0) {
                        indicatorData.push({name: item1.classifyName, max: item1.standardScore})
                      }
                    dataArr[index].value.push(item1.finalScore)
                    }
                  )

                })
              }
              this.initEcharts(indicatorData,dataArr)
            }
          })
      },
      initEcharts(indicatorData,dataArr){
        // 基于准备好的dom，初始化echarts实例
        var myChart = this.echarts.init(document.getElementById('echartRecordResult'));

        let option = {
          color: this.$store.state.colors,
          title: {
            text: '考核类别得分',
            textStyle: {
              fontSize: 15,
              fontWeight: 'bolder',
              color: '#3975FE'          // 主标题文字颜色
            },
          },
          tooltip: {},
          radar: {
//               shape: 'circle',
            center: ['50%', '55%'],
            name: {
              textStyle: {
                color: '#3975FE',
              }
            },
            indicator:indicatorData
          },
          series: [{
            name: '指标得分',
            type: 'radar',
            areaStyle: {
              normal: {
                opacity: 0.2
              }
            },
            data: dataArr
          }]
        };

        myChart.setOption(option);
        window.addEventListener("resize", function () {
          myChart.resize();
        });

      },
      getTempalteInfo(){
        //获取当前模板信息
        this.axios.post(process.env.API_HOST + `/examine/selectProceedingTask`, {})
          .then(response => {
            const result = response.data
            if (result.code == 200) {
              this.examineTask = result.result ? result.result : {}
              this.taskId = this.examineTask.id
            }
          })
        //获取历史列表
        this.axios.post(process.env.API_HOST + `/examine/selectSuccessTask`, {})
          .then(response => {
            const result = response.data
            if (result.code == 200) {
              this.options = result.result
              if (this.options.length > 0) {
                this.searchElectricInfo.taskId = this.options[0].id
                this.searchElectricInfo.taskIdRe = this.options[0].id
                this.searchElectricInfo.examineName = this.options[0].examineName
                //各期指标
                this.selectExamineItemGrade(this.searchElectricInfo.taskId)
                this.getExamineInfo(this.options[0].templateId, this.options[0].id)
              }
            }
          })
      },
      //获取所有信息
      getExamineInfo(templateId, taskId){
        this.axios.post(process.env.API_HOST + `/examine/selectEnterpriseTotalList`, {
          templateId: templateId,
          taskId: taskId
        })
          .then(response => {
            let result = response.data
            if (result.code == 200) {

              this.rows = []
              result.result.forEach(item => {
                item.itemList.forEach(item1 => {
                  this.rows.push({
                    ...item1,
                    classifyId: item.classifyId,
                    classifyName: item.classifyName,
                    classifyScore: ""
                  })
                })

              })
              this.tableCompanyList = []
              if (this.rows.length > 0) {
                this.rows[0].enterpriseTotalList.forEach((item, key) => {
                  this.$store.state.companyInfos.forEach(item1 => {
                    if (item.enterpriseNo == item1.enterpriseNo) {
                      this.tableCompanyList.push({enterpriseName: item1.enterpriseAlias, totalScore: item.totalScore})
                    }
                  })
                })
                this.spanArr = this.getSpanArr(this.rows, "classifyName")
                this.rows.forEach((item, key) => {
                  this.tableCompanyList.forEach((item1, index) => {
//                    item['value'+index]=item1.totalScore
                    item['value' + index] = item.enterpriseTotalList[index].totalScore
                  })
                  this.totalScore += item.standardScore
                  this.getclassifyScore(key)
                })
              }
            }
          })

      },
      objectSpanMethod({row, column, rowIndex, columnIndex}) {
        if (columnIndex === 0 || columnIndex === 1) {
          const _row = this.spanArr[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          };
        }
      },
      getclassifyScore(index){
        let sub = 0, isPass = true, classifyScore = 0
        this.spanArr.forEach(item => {
          sub += item
          if (isPass && sub > index) {
            isPass = false
            const sliceArr = this.rows.slice(sub - item, sub)
            sliceArr.forEach(item => {
              classifyScore += this.toDecimal(item.standardScore)
            })
            sliceArr.forEach(item => {
              item.classifyScore = classifyScore
            })
          }
        })

      },
      getSummaries(param) {
        let _this = this
        const {columns, data} = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '';
            return;
          } else if (index === 1) {
            sums[index] = '考核成绩';
            return;
          }
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return _this.toDecimal(prev + curr);
              } else {
                return prev;
              }
            }, 0);
            sums[index] += " 分"
          } else {
//            sums[index] = 'N/A';
            sums[index] = '';
          }
        });

        return sums;
      },
      //初步考核结果
      getcurrentTempalteInfo(){
        this.axios.post(process.env.API_HOST + `/examine/selectProceedingTask`, {})
          .then(response => {
            const result = response.data ? response.data : {}
            if (result.code == 200) {
              if (result.result.currentStatus == 0 || result.result.currentStatus == 4) {
                this.$message({
                  type: 'warning',
                  message: "暂无考核结果"
                });
                return
              }
              this.$router.push("/examinationResults/examinOpinions")
            } else {
              this.$message({
                type: 'warning',
                message: "暂无考核结果"
              });
            }
          })
      },
    },
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  @import "../../../common/stylus/mixin.styl"
  .examinationResultsWrap
    page()
</style>
